const domain = 'https://shop.oursite.tech';
import store from '../store/store.js'; 

var isToLogin = false;
const http = (url,param = {}) => {
	
	let obj = param.data ? param : { data:param };
	let token = uni.getStorageSync("loginToken");
	if(!token || token == '') {
		return;
	}
	uni.showLoading({
		mask:true
	})
	const t = this;
	return new Promise((resolve, reject) => {
		let postData = obj.data;
		postData.token = token;
		uni.request({
			url:domain + url,
			method: obj.method || "GET",
			data:postData,
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'Accept': 'application/json'
			},
			success:function(res) {
				uni.hideLoading();
				resolve(res)
			},
			fail: function(err) {
				this.$store.commit("setLogin",false);
				uni.removeStorage('loginToken');
				uni.hideLoading();
				uni.showToast({
					title: '网络请求超时，请稍后重试',
					icon: 'none'
				})
				reject(err)
			}
		})
	})	
}
let appSecret = 'd3601f6b2a46ea55cf46b79ab1c6dce8';
let appId = 'wx022a2117b6e96eb3';
const checkLogin = () => {
	let loginToken = uni.getStorageSync("loginToken");
	// console.log(loginToken);
	if(loginToken != '' && loginToken) {
		uni.login({
			provider:'weixin',
			success:(res) => {
				console.log(res)
				if(res.errMsg == 'login:ok') {
					uni.request({
						url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + appSecret + '&js_code=' + res.code + '&grant_type=authorization_code',
						data: {},
						header: {
						  'content-type': 'json'
						},success: (res) => {
							console.log(res);
							let {data,errMsg} = res;
							if(errMsg == 'request:ok') {
								console.log(domain + '/ajax/api.aspx')
								uni.request({
									url:domain + '/ajax/api.aspx',
									data:{
										token:loginToken,
										openid:data.openid,
										action:'CheckLogin'
									},
									success: (res2) => {
										console.log(res2)
										let {token, result} = res2.data;
										t.$store.commit("setLogin",true);
										uni.setStorage({
											'key':'loginToken',
											'data':token
										})
									},
									fail: (err2) => {
										console.log(err2)
										t.$store.commit('setLogin',false);
									}
								})
							}
						},
						fail: (err) => {
							console.log(err)
						}
					})
				}
			},
			fail:(err) => {
				console.log(err)
			}
		})
	}else {
		
	}
	
	// uni.request({
	// 	url:domain+'/ajax/api.aspx',
	// 	data:{
	// 		action:"CheckLogin",
	// 		token:loginToken,
	// 		openid:
	// 	},
	// 	header: {
	// 		'content-type': 'application/x-www-form-urlencoded',
	// 		'Accept': 'application/json'
	// 	},
	// 	dataType:"json"
	// }).then( res=> {
	// 	console.log(res)
	// }).catch(err =>{
	// 	console0.log(err)
	// })
}

export {
	http,
	checkLogin
}
